﻿using MediatR;
using MS.Data.API.Read.Command.Role;
using MS.Data.API.Read.Command.User;
using MS.Data.API.Read.DTO;
using MS.Data.Domain;
using MS.Data.ErrorCode;
using MS.Data.Infratructrue.Istanbul;

namespace MS.Data.API.Read.CommandHandle.Role
{
    /// <summary>
    /// 循环显示角色命令处理
    /// </summary>
    public class GetRoleCommandHandelr : IRequestHandler<GetRoleCommand, APIResult<ApiPagging<RoleDTO>>>
    {
        private readonly IBaseRepository<Domain.Role> repository;

        public GetRoleCommandHandelr(IBaseRepository<Domain.Role> repository)
        {
            this.repository = repository;
        }

        public Task<APIResult<ApiPagging<RoleDTO>>> Handle(GetRoleCommand request, CancellationToken cancellationToken)
        {
            APIResult<ApiPagging<RoleDTO>> result = new APIResult<ApiPagging<RoleDTO>>();
            result.code = APIEnum.显示成功;
            result.mes = APIEnum.显示成功.ToString();

            var list = from a in repository.GetAll()
                       where !a.IsDel
                       select new RoleDTO
                       {
                           RoleId = a.RoleId,
                           RoleName = a.RoleName,
                           PermissionNames = a.PermissionNames,
                           Times = a.Times,
                           State = a.State,
                           IsDel = a.IsDel,
                       };

            if (!string.IsNullOrEmpty(request.RoleName))
            {
                list = list.Where(x => x.RoleName.Contains(request.RoleName));
            }


            int totalcount = list.Count();
            int totalpage = (int)Math.Ceiling(totalcount * 1.0 / request.PageSize);
            list = list.Skip(request.PageSize * (request.PageIndex - 1)).Take(request.PageSize);
            ApiPagging<RoleDTO> page = new ApiPagging<RoleDTO>();

            page.TotalPage = totalpage;
            page.TotalCount = totalcount;
            page.Items = list.ToList();
            result.data = page;
            return Task.FromResult(result);
        }
    }
}
